
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QDateTime>

extern bool (*FastprRecognize)(const unsigned char *grayImage, const short width, const short height, short outRegion[4],unsigned short outResult[8]);

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->listWidget,SIGNAL(currentRowChanged(int)),this,SLOT(selectRowChanged(int)));
    connect(ui->btnOpendir,SIGNAL(clicked(bool)),this,SLOT(openDir(bool)));
}

void MainWindow::openDir(bool)
{
    auto path = QFileDialog::getExistingDirectory(this,"");
    if(path.isNull()) return;
    QDir dir(path);
    dir.setFilter(QDir::Files| QDir::NoDotAndDotDot);
    disconnect(ui->listWidget,SIGNAL(currentRowChanged(int)),this,SLOT(selectRowChanged(int)));
    ui->listWidget->clear();
    connect(ui->listWidget,SIGNAL(currentRowChanged(int)),this,SLOT(selectRowChanged(int)));
    auto fileInfos = dir.entryInfoList();
    for(int i=0;i<fileInfos.size();++i)
    {
        auto fileInfo = fileInfos.at(i);
        ui->listWidget->addItem(fileInfo.fileName());
        ui->listWidget->item(i)->setToolTip(fileInfo.absoluteFilePath());
    }
}

void MainWindow::selectRowChanged(int index)
{
    ui->lblResult->setText(QString::number(index));
    auto item = ui->listWidget->item(index);
    auto path = item->toolTip();
    QImage image(path);
    ui->lblImage->setPixmap(QPixmap::fromImage(image));
    const int width = image.width(), height = image.height();
    unsigned char *raw = new unsigned char[width * height];
    unsigned short ch[8] = { 0 };
    short region[4] = { 0 };
    for(int x=0;x<width;++x)
    {
        for(int y=0;y<height;++y)
        {
            raw[y*width + x] = (unsigned char)qGray(image.pixel(x,y));
        }
    }
    bool ret = (*FastprRecognize)(raw, width, height, region, ch);
    delete raw;
    if(ret)
    {
        int left = region[0], top = region[1], right = region[0] + region[2], bottom = region[1] + region[3];
        const unsigned int lineColor = 0xFFFF0000;
        for(int i = left; i <= right; ++i)
        {
            image.setPixel(i, top, lineColor);
            image.setPixel(i, bottom, lineColor);
        }
        for(int i = top; i <= bottom; ++i)
        {
            image.setPixel(left, i, lineColor);
            image.setPixel(right, i, lineColor);
        }
        QString result = QString::fromUtf16(ch);
        ui->lblResult->setText(result);
        ui->lblImage->setPixmap(QPixmap::fromImage(image));
    }else
    {
        ui->lblResult->setText("定位失败");
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
